package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")

public class LoginFilter implements Filter {
    //public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;

        HttpSession session = request1.getSession();
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend",
                "/front",
                "/user",
                };
        String requestURI = request1.getRequestURI();
        for (String loginUrl : loginUrls) {
            if (requestURI.contains(loginUrl)) {
                chain.doFilter(request, response);
                return;
            }
        }
       // System.out.println(session.getAttribute("UserId"));
        if (session.getAttribute("UserId") != null) {
            chain.doFilter(request, response);
            return;
        }
        if (session.getAttribute("LoginUser") != null) {
            chain.doFilter(request, response);
            return;
        }


        R r = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(r);
        response.getWriter().write(jsonString);

    }


}
